package com.conversationboard.model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import com.conversationboard.database.Queries;
import com.conversationboard.serialisation.XmlSerialiser;

/**
 * Class that stores a list of user privileges on a board by board basis.
 * 
 * @author Keith Watson
 * 
 */

public class PrivilegeList {

	private Map<Integer, Privileges> boardPrivileges = new HashMap<Integer, Privileges>();


	public Privileges getPrivileges(int boardId) {
		return this.boardPrivileges.get(boardId);
	}


	public void setPrivileges(int boardId, Privileges privileges) {

		boardPrivileges.put(boardId, privileges);
	}


	public static PrivilegeList deserialise(String xml) {

		XmlSerialiser<PrivilegeList> serialiser = new XmlSerialiser<PrivilegeList>();
		serialiser.setAlias("Privileges", Privileges.class);
		serialiser.setAlias("PrivilegeList", PrivilegeList.class);
		PrivilegeList privilegeList = serialiser.deSerialise(xml);

		return privilegeList;
	}


	private String serialise() {

		XmlSerialiser<PrivilegeList> serialiser = new XmlSerialiser<PrivilegeList>();
		serialiser.setAlias("Privileges", Privileges.class);
		serialiser.setAlias("PrivilegeList", PrivilegeList.class);

		String xml = serialiser.serialise(this);

		return xml;
	}


	public void store(String loginId, Connection connection) throws SQLException {

		String xml = this.serialise();

		PreparedStatement statement = connection.prepareStatement(Queries.USER_STORE_PRIVILEGE_LIST);
		statement.setString(1, xml);
		statement.setString(2, loginId);

		statement.executeUpdate();

		statement.close();
	}

}
